import React, { useState, useRef, useEffect } from 'react'
import ParkingMap from './ParkingMap'
import GuideEditor from './GuideEditor'
import DataDashboard from './DataDashboard'

export default function Park() {
  const [slots, setSlots] = useState([
    { id: 'A1', x: 100, y: 100, occupied: false },
    { id: 'A2', x: 200, y: 100, occupied: true },
    { id: 'B1', x: 100, y: 200, occupied: false },
  ])
  const [guides, setGuides] = useState([])
  const [startSlot, setStartSlot] = useState(null)
  const canvasRef = useRef(null)

  const handleSlotClick = (e) => {
    const rect = canvasRef.current.getBoundingClientRect()
    const clickPos = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    }

    const clickedSlot = slots.find(
      (s) =>
        clickPos.x >= s.x &&
        clickPos.x <= s.x + 60 &&
        clickPos.y >= s.y &&
        clickPos.y <= s.y + 30
    )

    if (startSlot) {
      if (clickedSlot && clickedSlot.id !== startSlot.id) {
        setGuides([
          ...guides,
          {
            id: `guide_${Date.now()}`,
            start: { x: startSlot.x + 30, y: startSlot.y + 15 },
            end: { x: clickedSlot.x + 30, y: clickedSlot.y + 15 },
          },
        ])
      }
      setStartSlot(null)
    } else if (clickedSlot) {
      setStartSlot(clickedSlot)
    }
  }

  return (
    <div style={{ display: 'flex' }}>
      <div>
        <canvas
          ref={canvasRef}
          width={500}
          height={400}
          onClick={handleSlotClick}
          style={{ border: '1px solid #000' }}
        />
        <ParkingMap
          canvasRef={canvasRef}
          slots={slots}
          guides={guides}
          startSlot={startSlot}
        />
      </div>
      <GuideEditor guides={guides} startSlot={startSlot} />
    </div>
  )
}
